package com.sbio.udiapp.ui;

import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.blankj.utilcode.util.LogUtils;
import com.sbio.udiapp.BuildConfig;
import com.sbio.udiapp.R;
import com.sbio.udiapp.adapter.ListViewAdapter;
import com.sbio.udiapp.common.bean.PrintVo;
import com.sbio.udiapp.common.bean.RequestUniParam;
import com.sbio.udiapp.cpcl.PrintUtil;
import com.sbio.udiapp.databinding.ActivityRawMaterialBinding;
import com.sbio.udiapp.di.ActivityManager;
import com.sbio.udiapp.listener.ListViewAdapterListener;
import com.sbio.udiapp.net.api.ApiService;
import com.sbio.udiapp.net.bean.AjaxResult;
import com.sbio.udiapp.ui.model.RawMaterialListItemView;
import com.sbio.udiapp.util.ApiServiceUtil;
import com.sbio.udiapp.util.DialogUtil;
import com.sbio.udiapp.util.LogUtil;
import com.sbio.udiapp.util.SharedPreferencesUtil;
import com.sbio.udiapp.util.SoundPlayerUtil;
import com.sbio.udiapp.util.ToastUtil;

import java.util.Base64;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import cpcl.PrinterHelper;
import dagger.hilt.android.AndroidEntryPoint;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@AndroidEntryPoint
public class RawMaterialActivity extends BaseBroadCastActivity implements ListViewAdapterListener<RawMaterialListItemView> {


    ActivityRawMaterialBinding binding;

    @Inject
    ApiService apiService;

    ObservableList<RawMaterialListItemView> dataList = new ObservableArrayList<>();

    ListViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRawMaterialBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        //初始化数据
        initData();

        SharedPreferencesUtil.init(this);

        //初始化nos监听器
        initListViewListener();

        //绑定提交业务
        /*binding.submit.setOnClickListener(v -> {

            String billNo = binding.billNo.getText().toString();

            if (StringUtils.isEmpty(billNo)) {
                ToastUtil.showError("请先填写电子面单数量");
                return;
            }
            if (CollectionUtils.isEmpty(nos)) {
                ToastUtil.showError("请先扫码添加发货单");
                return;
            }

            String requestUniParam = RequestUniParam.create("提交RawMaterialActivity").toJson();
            showProcess();
            ApiServiceUtil.enqueue(() -> apiService.havePrint(expressPage.getPageNo()), new Callback<AjaxResult>() {
                @Override
                public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                    hideProcess();
                    AjaxResult ajaxResult = response.body();

                    Map<String, Object> data = ajaxResult.getData(Map.class);
                    List<String> havePrintBillNos = (List<String>) data.get("havePrintBillNos");
                    boolean havePrintNosOfSameAddress = (Boolean) data.get("havePrintNosOfSameAddress");
                    AtomicInteger printFlag = new AtomicInteger();
                    if (havePrintBillNos.isEmpty() && !havePrintNosOfSameAddress) {
                        printRawMaterialBarcode(waybillCountInt, requestUniParam);
                        return;
                    }
                    StringBuilder msg = new StringBuilder();
                    List<String> msgs = new ArrayList<>();
                    if (!havePrintBillNos.isEmpty()) {
                        msgs.add("以下单据编号今天已经打印过了:\n" + String.join(",", havePrintBillNos));
                    }
                    if (havePrintNosOfSameAddress) {
                        msgs.add("该地址今天已经打印过快递单");
                    }
                    if (msgs.isEmpty()) {
                        printRawMaterialBarcode(waybillCountInt, requestUniParam);
                    } else {
                        for (int i = 0; i < msgs.size(); i++) {
                            msg.append((i + 1)).append(".").append(msgs.get(i)).append("\n");
                        }
                        DialogUtil.showCommonConfirmDialog(msg.toString(), () -> printRawMaterialBarcode(waybillCountInt, requestUniParam));
                    }


                }

                @Override
                public void onFailure(Call<AjaxResult> call, Throwable t) {
                    hideProcess();
                    DialogUtil.showErrorAlertDialog(t.getMessage());
                }
            });

        });*/
    }

    private void printRawMaterialBarcode(String billNo, String requestUniParam) {
        showProcess();
        long startTime = System.currentTimeMillis();
        int printNum = 0;//打印数量
        ApiServiceUtil.enqueue(() -> apiService.printRawMaterialBarcode(billNo, printNum, requestUniParam), new Callback<AjaxResult>() {
            @Override
            public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                hideProcess();
                try {
                    AjaxResult ajaxResult = response.body();
                    if (ajaxResult.getCode() == 500) {
                        ToastUtil.showError(ajaxResult.getMsg());
                        return;
                    }
                    List<String> imageBase64s = ajaxResult.getDataListByClz(String.class);

                    for (String imageBase64 : imageBase64s) {

                        byte[] decode = Base64.getDecoder().decode(imageBase64);
                        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);

                        int s1 = 75 * 8;
                        int s2 = 105 * 8;

                        PrinterHelper.printAreaSize("0", String.valueOf(s1), String.valueOf(s2), String.valueOf(s2), "1");
                        PrinterHelper.printBitmapCPCL(bitmap, 0, 0, 0, 0, 0);
                        PrinterHelper.Form();
                        PrinterHelper.Print();
                    }
                    LogUtils.i("时间：", System.currentTimeMillis() - startTime);
                    if (ajaxResult.isSuccess()) {
                        ToastUtil.show("打印成功");
                        if (!BuildConfig.DEBUG) {
                            RawMaterialActivity.this.reset();
                        }
                    } else {
                        DialogUtil.showCommonAlertDialog("打印失败" + ajaxResult.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtil.file("print", e.getMessage());
                    DialogUtil.showCommonAlertDialog("打印失败" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<AjaxResult> call, Throwable t) {
                hideProcess();
                DialogUtil.showErrorAlertDialog(t.getMessage());
            }
        });
    }


    private void reset() {

        showProcess();
        hideProcess();
    }

    private void initData() {

    }

    //初始化listView监听器
    private void initListViewListener() {
        //初始化nos listView布局
        binding.dataListView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ListViewAdapter<>(dataList, this);
        binding.dataListView.setAdapter(adapter);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
//        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.custom_divider)); // 设置自定义分割线样式
        binding.dataListView.addItemDecoration(dividerItemDecoration);
        binding.dataListView.setItemAnimator(new DefaultItemAnimator());

        dataList.addOnListChangedCallback(new ObservableList.OnListChangedCallback<ObservableList<RawMaterialListItemView>>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onChanged(ObservableList<RawMaterialListItemView> sender) {
                adapter.notifyDataSetChanged(); // 数据变化时通知适配器刷新列表
            }

            @Override
            public void onItemRangeChanged(ObservableList<RawMaterialListItemView> sender, int positionStart, int itemCount) {
                adapter.notifyItemRangeChanged(positionStart, itemCount); // 通知适配器局部刷新
            }

            @Override
            public void onItemRangeInserted(ObservableList<RawMaterialListItemView> sender, int positionStart, int itemCount) {
//                adapter.notifyItemRangeChanged(positionStart-1, itemCount); // 通知适配器局部刷新
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onItemRangeMoved(ObservableList<RawMaterialListItemView> sender, int fromPosition, int toPosition, int itemCount) {
                adapter.notifyItemRangeRemoved(fromPosition, itemCount); // 通知适配器局部刷新
            }

            @Override
            public void onItemRangeRemoved(ObservableList<RawMaterialListItemView> sender, int positionStart, int itemCount) {
                adapter.notifyItemRangeRemoved(positionStart, itemCount); // 通知适配器局部刷新
            }
        });
    }


    @Override
    public void onBroadcastReceiver(String barcodeData) {
        LogUtil.file("接收到广播数据", barcodeData);
        if (progressCount.get() > 0) {
            ToastUtil.showWait("请等待上一个结果返回");
            return;
        }
        if (dataList.contains(barcodeData)) {
            ToastUtil.showError("数据重复");
            return;
        }
        //如果是出库申请开头的数据那么就是outStockApplyNos
        if (barcodeData.indexOf("CGSL") == 0) {
            binding.billNo.setText(barcodeData);
            loadListView(barcodeData);
        } else {
            //非法数据
            ToastUtil.showError("非法数据，请检查");
            return;
        }
    }


    public void loadListView(String billNo) {
        showProcess();
        ApiServiceUtil.enqueue(() -> apiService.getReceiveBill(billNo), new Callback<AjaxResult>() {
            @Override
            public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                hideProcess();
                AjaxResult ajaxResult = response.body();
                if (Objects.requireNonNull(ajaxResult).isSuccess()) {
                    List<RawMaterialListItemView> views = ajaxResult.getDataListByClz(RawMaterialListItemView.class);
                    dataList.clear();
                    dataList.addAll(views);
                    ToastUtil.showSuccess("查询成功");
                } else {
                    DialogUtil.showErrorAlertDialog(ajaxResult.getMsg());
                }
            }

            @Override
            public void onFailure(Call<AjaxResult> call, Throwable t) {
                hideProcess();
                DialogUtil.showErrorAlertDialog(t.getMessage());
            }
        });
    }


    /*@Override
    protected void onResume() {
        super.onResume();
        // 注册广播接收器
        registerReceiver(broadcastReceiver, intentFilter);
    }*/

    /**
     * 保存页面数据
     */
    private void saveExpress(Runnable r1) {
        String requestUniParam = RequestUniParam.create("保存页面数据").toJson();
        showProcess();

       /* ApiServiceUtil.enqueue(() -> apiService.saveExpress(expressPageCopy, requestUniParam), new Callback<AjaxResult>() {
            @Override
            public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                hideProcess();
                AjaxResult ajaxResult = response.body();
                if (Objects.requireNonNull(ajaxResult).isSuccess()) {

                    String count = ajaxResult.getData(String.class);
                    ToastUtil.showSuccess("保存成功");
                    Optional.ofNullable(r1).ifPresent(Runnable::run);
                } else {
                    SoundPlayerUtil.playFail();
                    DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                }
            }

            @Override
            public void onFailure(Call<AjaxResult> call, Throwable t) {
                hideProcess();
                DialogUtil.showErrorAlertDialog(t.getMessage());
            }
        });*/
    }


   /* @Override
    protected void onPause() {
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver); // 取消广播注册
        }
        super.onPause();
    }*/

    @Override
    public void btn(RawMaterialListItemView datum) {


        Context context = ActivityManager.getCurrentActivity();

        // 加载自定义布局
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_custom_input, null);
        EditText etInput1 = view.findViewById(R.id.et_input1);
        etInput1.setHint("请输入数量");
        etInput1.setText(datum.getQty().toString());
        etInput1.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        EditText etInput2 = view.findViewById(R.id.et_input2);
        etInput2.setHint("请输入箱数");
        etInput2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        etInput2.setText("1");
        EditText etInput3 = view.findViewById(R.id.et_input3);
        etInput3.setHint("请输入尾数");
        etInput3.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        etInput3.setText("0");

        // 构建 AlertDialog
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("确认打印原材料二维码?")
                .setView(view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String input1 = etInput1.getText().toString();
                        Integer input2 = null;
                        try {
                            input2 = Integer.valueOf(etInput2.getText().toString());
                        } catch (NumberFormatException e) {
                            input2 = 1;
                        }
                        Integer input3 = null;
                        try {
                            input3 = Integer.valueOf(etInput3.getText().toString());
                        } catch (NumberFormatException e) {
                            input3 = 0;
                        }

                        Integer finalInput2 = input2;
                        Integer finalInput3 = input3;
                        ApiServiceUtil.enqueue(() -> apiService.printRawMaterial(datum, finalInput2, finalInput3), new Callback<AjaxResult>() {
                            @Override
                            public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                                hideProcess();
                                AjaxResult ajaxResult = response.body();
                                if (Objects.requireNonNull(ajaxResult).isSuccess()) {

                                    List<RawMaterialListItemView> views = ajaxResult.getDataListByClz(RawMaterialListItemView.class);
                                    views.forEach(it->it.setQty(Long.parseLong(input1)));
                                    views.forEach(it->{
                                        PrintUtil.printRawMaterial4ReceiveBill(it);
                                        try {
                                            Thread.sleep(1000);
                                        } catch (InterruptedException e) {
                                            throw new RuntimeException(e);
                                        }
                                    });
//                                    views.forEach(PrintUtil::printRawMaterial);
                                    ToastUtil.showSuccess("打印成功");
                                    //            PrintUtil.printQR4Product(new PrintVo());
                                } else {
                                    SoundPlayerUtil.playFail();
                                    DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                                }
                            }

                            @Override
                            public void onFailure(Call<AjaxResult> call, Throwable t) {
                                hideProcess();
                                DialogUtil.showErrorAlertDialog(t.getMessage());
                            }
                        });
                    }
                })
                .setNegativeButton("取消", null)
                .show();


    }
}